﻿// -----------------------------------------------------------------------
// <copyright file="MessageProcessorService.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace TPTecnicas.MessageProcessor.Services
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;
    using System.Configuration;
    using TPTecnicas.MessageProcessor.Services.Interfaces;
    using TPTecnicas.MessageProcessor.Common;
    using TPTecnicas.MessageProcessor.Services.EmailSenderService;
    using TPTecnicas.MessageProcessor.Persistence;
    using TPTecnicas.MessageProcessor.Business;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel.Composition.Primitives;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class MessageProcessorService : IMessageProcessorService
    {
        private readonly EmailSenderClient _emailSenderClient;
        private readonly IDictionary<string, IRule> _rules;
        private readonly IUniversityContext _context;
        private readonly XDocument _destinataryRules;
        private readonly PluginsRepository _pluginsRepository;

        public MessageProcessorService()
        {
            //_emailSenderClient = new EmailSenderClient();
            _context = new InMemoryContext();
            _destinataryRules = XDocument.Load(ConfigurationManager.AppSettings["destinataryRulesPath"]);

            try
            {
                var catalog = new DirectoryCatalog(@ConfigurationManager.AppSettings["pluginsPath"]);
                var container = new CompositionContainer(catalog);
                container.ComposeExportedValue("context", _context);
                _pluginsRepository = new PluginsRepository()
                {
                    Rules = container.GetExportedValues<IRule>(),
                    Actions = container.GetExportedValues<IAction>()
                };
            }
            catch (Exception ex)
            {
                ;
            }


            _rules = new Dictionary<string, IRule>();
            foreach (IRule rule in _pluginsRepository.Rules)
            {
                _rules.Add(rule.GetType().Name, rule);
            }
            
            //TODO Lazy mount de reglas y acciones
        }
        public void ProcessMessage(Message message)
        {
            //TODO aplicar reglas dependiendo el mensaje

            var rulesIds = _destinataryRules.Root.Elements()
                .Where(d => d.Attribute("id").Value.Equals(message.Destinatary))
                .Elements("rules").Descendants()
                .Select(r => r.Name.LocalName);

            foreach (var ruleId in rulesIds)
            {
                try
                {
                    _rules[ruleId].Validate(message);
                }
                catch (Exception ex)
                {
                    //TODO
                }
            }

            //_emailSenderClient.SendMail(new Message() { Sender = "Nico", Destinatary = "Anyone", Subject = "Hello Mail" });
        }
    }
}
